package com.sk.sourcecircle.activity.home.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dyhdyh.widget.loading.dialog.LoadingDialog;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.tools.PictureFileUtils;
import com.sk.sourcecircle.R;
import com.sk.sourcecircle.activity.mine.act.PreviewViewpagerActivity;
import com.sk.sourcecircle.adapter.ReleasePictureAdapter;
import com.sk.sourcecircle.app.MyApplication;
import com.sk.sourcecircle.base.BaseActivity;
import com.sk.sourcecircle.callback.HandleDataCallBack;
import com.sk.sourcecircle.callback.MyCallBack;
import com.sk.sourcecircle.dialog.ReleaseChooseDialogFragment;
import com.sk.sourcecircle.entity.GroupListBean;
import com.sk.sourcecircle.utils.AppApi;
import com.sk.sourcecircle.utils.HttpAddress;
import com.sk.sourcecircle.utils.MD5;
import com.sk.sourcecircle.utils.MyUtils;
import com.sk.sourcecircle.utils.SnackUtils;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by sk on 2017/11/29.
 */

public class ReleaseAlbumActivity extends BaseActivity implements MyCallBack, BaseQuickAdapter.OnItemClickListener, HandleDataCallBack {


    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.release)
    TextView release;
    @BindView(R.id.ed_content)
    EditText edContent;
    @BindView(R.id.album_ryc)
    RecyclerView albumRyc;
    private ReleasePictureAdapter releasePictureAdapter;
    List<GroupListBean.DataBean> dataBeanList = new ArrayList<>();

    private List<LocalMedia> allList = new ArrayList<>();
    private List<LocalMedia> pictureList = new ArrayList<>();
    private LoadingDialog loadingDialog;
    private int count = 0;
    private StringBuilder builder;
    private String groupId;

    @Override
    protected int getContentView() {
        return R.layout.activity_release_album;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        AppApi.getJoinedGroup(this, 0, this);
        loadingDialog = MyUtils.getLoadingDialog(mContext, false);

        allList.add(new LocalMedia());
        albumRyc.setLayoutManager(new GridLayoutManager(this, 4));
        releasePictureAdapter = new ReleasePictureAdapter(R.layout.item_release_pic, allList);
        albumRyc.setAdapter(releasePictureAdapter);

        releasePictureAdapter.setOnItemClickListener(this);
    }


    @OnClick({R.id.back, R.id.release})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.release:

                if (isFormat()) {
                    ReleaseChooseDialogFragment releaseChooseDialogFragment = new ReleaseChooseDialogFragment();
                    releaseChooseDialogFragment.setDataBeanList(dataBeanList);
                    releaseChooseDialogFragment.setMyCallBack(ReleaseAlbumActivity.this);
                    releaseChooseDialogFragment.show(getSupportFragmentManager(), "choose");
                }
                break;
        }
    }

    private boolean isFormat() {
        if (TextUtils.isEmpty(edContent.getText().toString())) {
            SnackUtils.showError(mRootView, "请您输入要发布的内容!");
            return false;
        }
        if (pictureList.size() <= 0) {
            SnackUtils.showError(mRootView, "至少上传一张图片!");
            return false;
        }
        return true;
    }


    @Override
    public void releaseAlbum() {

    }

    @Override
    public void joinGroup() {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    @Override
    public void takePhoto() {

    }

    @Override
    public void choosePhoto() {


    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        if (position == 0) {
            PictureSelector.create(ReleaseAlbumActivity.this)
                    .openGallery(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                    .maxSelectNum(9)// 最大图片选择数量 int
                    .imageSpanCount(4)// 每行显示个数 int
                    .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                    .previewImage(true)// 是否可预览图片 true or false
                    .isCamera(true)// 是否显示拍照按钮 true or false
                    .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                    .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                    .sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                    .enableCrop(false)// 是否裁剪 true or false
                    .compress(true)// 是否压缩 true or false
                    .compressSavePath(Environment.getExternalStorageDirectory().getPath())//压缩图片保存地址
                    .selectionMedia(pictureList)// 是否传入已选图片 List<LocalMedia> list
                    .previewEggs(true)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中) true or false
                    .cropCompressQuality(90)// 裁剪压缩质量 默认90 int
                    .minimumCompressSize(100)// 小于100kb的图片不压缩
                    .synOrAsy(true)//同步true或异步false 压缩 默认同步
                    .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
        } else {
            ArrayList<String> stringList = new ArrayList<>();
            for (LocalMedia media : pictureList) {
                stringList.add(media.getPath());
            }
            Intent intent = new Intent(mContext, PreviewViewpagerActivity.class);
            intent.putExtra("pos", position - 1);
            intent.putExtra("type", 0);
            intent.putStringArrayListExtra("list", stringList);
            startActivity(intent);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    pictureList.clear();
                    pictureList.addAll(selectList);
                    allList.clear();
                    allList.add(new LocalMedia());
                    allList.addAll(pictureList);
                    releasePictureAdapter.notifyDataSetChanged();
                    break;
            }
        }
    }

    private void upLoadAppendixImg(final Bitmap bitmap) {
        RequestParams requestParams = new RequestParams(HttpAddress.TestIp + HttpAddress.UploadImage);
        requestParams.addBodyParameter("img_url", MyUtils.bitmapToBase64(bitmap));
        long timeStamp = System.currentTimeMillis();
        requestParams.addBodyParameter("timestamp", String.valueOf(timeStamp));
        requestParams.addBodyParameter("token", MyUtils.getToken(mContext));
        requestParams.addBodyParameter("sign", MD5.md5(timeStamp + "_yuanquan"));
        x.http().post(requestParams, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.v("upLoadAppendixImg", result);
                if (count == pictureList.size() - 1) {
                    clearCache();
                    com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(result);
                    String imageUrl = jsonObject.getString("data");
                    builder.append(imageUrl);
                    Log.v("upLoadAppendixImg", builder.toString());
                    AppApi.upLoadAlbum(String.valueOf(MyApplication.getInstance().getLat()), String.valueOf(MyApplication.getInstance().getLng()), edContent.getText().toString(), builder.toString(), 0, groupId, ReleaseAlbumActivity.this, 1, ReleaseAlbumActivity.this);
                } else {
                    com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(result);
                    String imageUrl = jsonObject.getString("data");
                    builder.append(imageUrl).append(",");
                    count++;
                    Bitmap bitmap = null;
                    if (pictureList.get(count).isCompressed()) {
                        bitmap = BitmapFactory.decodeFile(pictureList.get(count).getCompressPath());
                    } else {
                        bitmap = BitmapFactory.decodeFile(pictureList.get(count).getPath());
                    }
                    upLoadAppendixImg(bitmap);
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.v("upLoadAppendixImg", ex.toString());
                loadingDialog.cancelDialog();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private void clearCache() {
        PictureFileUtils.deleteCacheDirFile(ReleaseAlbumActivity.this);
    }

    @Override
    public void handlerSuccessData(String result, int tag) {
        switch (tag) {
            case 0:
                GroupListBean groupListBean = JSON.parseObject(result, GroupListBean.class);
                dataBeanList = groupListBean.getData();
                break;
            case 1:
                loadingDialog.cancelDialog();
                finish();
                Toast.makeText(mContext, "发布成功!", Toast.LENGTH_SHORT).show();
                break;
        }
    }

    @Override
    public void handlerFailData(String failString, int tag) {
        loadingDialog.cancelDialog();
    }

    @Override
    public void handleErrorData(String error, int tag) {
        loadingDialog.cancelDialog();
    }

    @Override
    public void chooseGroup(String id) {
        super.chooseGroup(id);
        groupId = id;

        //发布相册
        if (pictureList.size() > 0) {
            count = 0;
            loadingDialog.show();
            builder = new StringBuilder();
            if (pictureList.get(0).isCompressed()) {
                Bitmap bitmap = BitmapFactory.decodeFile(pictureList.get(0).getCompressPath());
                upLoadAppendixImg(bitmap);
            } else {
                Bitmap bitmap = BitmapFactory.decodeFile(pictureList.get(0).getPath());
                upLoadAppendixImg(bitmap);
            }
        } else {
            loadingDialog.show();
            AppApi.upLoadAlbum(String.valueOf(MyApplication.getInstance().getLat()), String.valueOf(MyApplication.getInstance().getLng()), edContent.getText().toString(), null, 0, String.valueOf(groupId), ReleaseAlbumActivity.this, 1, ReleaseAlbumActivity.this);
        }
    }


}
